/**
* Web页面来实现todo-list的功能，学会URL的处理方式
* 
**/

var http = require('http');
var qs = require('querystring');
var items = [];

var server = http.createServer(function(req,res){
  if('/' == req.url){
    switch(req.method){
      case 'GET':
        show(res);
        break;
      case 'POST':
        add(req,res);
        break;
      default:
        badReq(res);
    }
  }else if(req.url.slice(0,5) == '/del/'){
    del(req,res);
  }else{
    noFound(res);
  }
});

server.listen(9000);
console.log('Server is started @9000');

function del(req,res){
  var deleteId = parseInt(req.url.slice(5)) -1;  // 排序从0开始，而显示从1开始
    if(isNaN(deleteId)){
      res.end('Invalid item id！\n');
    }else if(!items[deleteId]){
      res.end('Item not found！\n');
    }else{
      items.splice(deleteId , 1);
      show(res);
    }
}

function show(res){
  var item = '';
  var pageContent1 = '<html><head><title>Todo List</title></head><body>'
    + '<h1> Todo List </h1>'
    + '<ol>';
  var pageContent2 = '';
  for (var i = 0; i < items.length; i++) {
    pageContent2 += '<li>' + items[i] + '</li>';
  };
  var pageContent3 = '</ol>'
    + '<form method="POST" action="/">'
    + '<input type="text" name="name"><br/>'
    + '<input type="submit" value="add a list"><br/>'
    + '</form>';
  var pageContent = pageContent1 + pageContent2 + pageContent3;
  res.setHeader("content-type","text/html");
  res.end(pageContent);
}

function add(req,res){
  var body = '';
  req.on('data',function (chunk) {
    body += chunk;
  });
  req.on('end',function(){
    var list = qs.parse(body);
    items.push(list.name);
    show(res);
  });
}

function badReq(res){
  res.statusCode = 500;
  res.end('Bad Request!');
}
function noFound(res){
  res.statusCode = 404;
  res.end('Not Found!');
}